const { Service } = require('egg')
const { tableToList } = require('../utils/tools')

module.exports = class PlanService extends Service {
  /**
   * *培养计划
   * @return {Array} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/pyfa/pyfa_query`
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        Host: 'webvpn.hnust.edu.cn',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0',
      },
      timeout: 10000,
    })
    const header = ['课程名称', '属性', '性质', '学分', '考核方式', '学时', '开课院系'] // 列名称
    // eslint-disable-next-line no-tabs
    /* ['序号'	'开课学期'	'课程编号'	'课程名称'	'开课单位'	'学分'	'总学时'	'考核方式'	'课程性质'	'课程属性'	'是否考试'] */
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList')
        console.log(res.data.toString())
        const columnNeed = [3, 9, 8, 5, 7, 6, 4]
        const info = {}
        for (let i = 1; i < tableList.length; i++) {
          const term = tableList[i][1]
          if ((term in info) === false) { info[term] = [] }
          const tem = []
          columnNeed.forEach((idx) => {
            tem.push(tableList[i][idx] || '')
          })
          info[term].push(tem)
        }
        return { table: info, header, status: true }
      } catch (err) {
        return err
      }
    }
    return { table: {}, header, status: false }
  }
}
